import { Eko, LLMs, Agent } from "@eko-ai/eko";
import { BrowserAgent } from "@eko-ai/eko-extension";

/**
 * MCP 配置接口
 */
export interface MCPConfig {
  type: 'http' | 'sse';
  url: string;
  tools?: string[];
  headers?: Record<string, string>;
}

/**
 * 扩展的 Eko 配置，包含 MCP 支持
 */
interface ExtendedEkoConfig {
  llms: LLMs;
  agents?: Agent[];
  mcpConfigs?: MCPConfig[];
  callback?: any;
}

/**
 * 创建带有 MCP 功能的 Eko 实例
 */
export async function createEkoWithMCP(config: ExtendedEkoConfig): Promise<Eko> {
  // 基础代理
  const agents = config.agents || [new BrowserAgent()];
  
  // 如果配置了 MCP，则添加 MCP 工具
  if (config.mcpConfigs && config.mcpConfigs.length > 0) {
    for (const mcpConfig of config.mcpConfigs) {
      await addMCPTools(agents, mcpConfig);
    }
  }

  return new Eko({
    llms: config.llms,
    agents,
    callback: config.callback,
  });
}

/**
 * 添加 MCP 工具到代理
 */
async function addMCPTools(agents: Agent[], mcpConfig: MCPConfig): Promise<void> {
  try {
    if (mcpConfig.type === 'http') {
      await addHTTPMCPTools(agents, mcpConfig);
    } else if (mcpConfig.type === 'sse') {
      await addSSEMCPTools(agents, mcpConfig);
    }
  } catch (error) {
    console.error('Failed to add MCP tools:', error);
  }
}

/**
 * 添加 HTTP 类型的 MCP 工具
 */
async function addHTTPMCPTools(agents: Agent[], config: MCPConfig): Promise<void> {
  // 获取可用的工具列表
  const response = await fetch(`${config.url}/tools`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      ...config.headers,
    },
  });

  if (!response.ok) {
    throw new Error(`Failed to fetch MCP tools: ${response.statusText}`);
  }

  const toolsData = await response.json();
  const tools = toolsData.tools || [];

  // 为每个工具创建代理方法
  for (const tool of tools) {
    if (!config.tools || config.tools.includes(tool.name)) {
      addToolToAgents(agents, tool, config);
    }
  }
}

/**
 * 添加 SSE 类型的 MCP 工具
 */
async function addSSEMCPTools(agents: Agent[], config: MCPConfig): Promise<void> {
  // SSE 连接实现
  const eventSource = new EventSource(config.url);
  
  eventSource.onopen = () => {
    console.log('MCP SSE connection opened');
  };

  eventSource.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      handleMCPMessage(agents, data, config);
    } catch (error) {
      console.error('Failed to parse MCP SSE message:', error);
    }
  };

  eventSource.onerror = (error) => {
    console.error('MCP SSE connection error:', error);
  };

  // 存储连接以便后续使用
  (config as any).eventSource = eventSource;
}

/**
 * 处理 MCP SSE 消息
 */
function handleMCPMessage(agents: Agent[], message: any, config: MCPConfig): void {
  if (message.type === 'tool_available') {
    if (!config.tools || config.tools.includes(message.tool.name)) {
      addToolToAgents(agents, message.tool, config);
    }
  }
}

/**
 * 将工具添加到代理中
 */
function addToolToAgents(agents: Agent[], tool: any, config: MCPConfig): void {
  const toolFunction = createToolFunction(tool, config);
  
  // 将工具添加到第一个代理（通常是 BrowserAgent）
  if (agents.length > 0) {
    const agent = agents[0] as any;
    if (agent.addTool) {
      agent.addTool(tool.name, toolFunction, tool.description || '');
    } else {
      // 如果代理没有 addTool 方法，直接添加到代理的工具集合中
      if (!agent.tools) {
        agent.tools = {};
      }
      agent.tools[tool.name] = toolFunction;
    }
  }
}

/**
 * 创建工具函数
 */
function createToolFunction(tool: any, config: MCPConfig) {
  return async (params: any) => {
    try {
      if (config.type === 'http') {
        return await callHTTPTool(tool, params, config);
      } else if (config.type === 'sse') {
        return await callSSETool(tool, params, config);
      }
    } catch (error) {
      console.error(`Error calling MCP tool ${tool.name}:`, error);
      throw error;
    }
  };
}

/**
 * 调用 HTTP MCP 工具
 */
async function callHTTPTool(tool: any, params: any, config: MCPConfig): Promise<any> {
  const response = await fetch(`${config.url}/tools/${tool.name}/call`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      ...config.headers,
    },
    body: JSON.stringify({
      arguments: params,
    }),
  });

  if (!response.ok) {
    throw new Error(`MCP tool call failed: ${response.statusText}`);
  }

  const result = await response.json();
  return result.content || result;
}

/**
 * 调用 SSE MCP 工具
 */
async function callSSETool(tool: any, params: any, config: MCPConfig): Promise<any> {
  return new Promise((resolve, reject) => {
    const eventSource = (config as any).eventSource;
    
    if (!eventSource) {
      reject(new Error('SSE connection not available'));
      return;
    }

    // 发送工具调用请求
    const requestId = Date.now().toString();
    const message = {
      id: requestId,
      method: 'tools/call',
      params: {
        name: tool.name,
        arguments: params,
      },
    };

    // 监听响应
    const messageHandler = (event: MessageEvent) => {
      try {
        const data = JSON.parse(event.data);
        if (data.id === requestId) {
          eventSource.removeEventListener('message', messageHandler);
          if (data.error) {
            reject(new Error(data.error.message || 'MCP tool call failed'));
          } else {
            resolve(data.result);
          }
        }
      } catch (error) {
        reject(error);
      }
    };

    eventSource.addEventListener('message', messageHandler);

    // 发送消息（这里需要根据实际的 SSE 服务器实现来调整）
    // 通常 SSE 是单向的，可能需要通过其他方式发送请求
    console.log('Sending MCP tool call:', message);
  });
}

/**
 * MCP 工具定义示例
 */
export const exampleMCPConfigs: MCPConfig[] = [
  {
    type: 'http',
    url: 'http://localhost:3000/mcp',
    tools: ['web_search', 'file_read', 'database_query'],
    headers: {
      'Authorization': 'Bearer your-api-key',
    },
  },
  {
    type: 'sse',
    url: 'http://localhost:3001/mcp/events',
    tools: ['realtime_data', 'live_notifications'],
  },
];

/**
 * 工具定义的 JSON DSL 示例（遵循 Eko 规范）
 */
export const mcpToolNodeExample = {
  id: "mcp-web-search",
  type: "action",
  name: "MCP Web Search",
  action: {
    type: "script",
    name: "web_search",
    params: {
      query: "${searchQuery}",
      maxResults: 10,
      source: "mcp"
    }
  },
  output: {
    type: "array",
    schema: {
      type: "array",
      items: {
        type: "object",
        properties: {
          title: { type: "string" },
          url: { type: "string" },
          snippet: { type: "string" }
        }
      }
    }
  }
};